package com.gtenacg.cartoonservice.compent;

import com.gtenacg.cartoonservice.common.Result;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Component
public class MyRestTemplate {
    private MyRestTemplate() {
    }

    final static RestTemplate restTemplate = new RestTemplate();
    private static String baseUrl;

    @Value("${my-config.fileServer.baseUrl}")
    private String tempBaseUrl;

    @PostConstruct
    public void setBaseUrl() {
        baseUrl = this.tempBaseUrl;
    }

    public static List<String> FileServiceGetChapter(String target, Boolean isInfos) {
        target = target.replace("/filePath", "");
        String url = null;
        if (isInfos) {
            url = baseUrl + "/list?filePath={target}&getFile=true";
        } else {
            url = baseUrl + "/list?filePath={target}&getFile=false";
        }
        ResponseEntity<List<String>> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<String>>() {
                },
                Map.of("target", target)
        );
        if (response.getStatusCode() == HttpStatus.OK) {
            return response.getBody();
        }
        log.error("请求失败？？？-> FileServiceGetChapterList");
        System.err.println("response.toString() = " + response);
        return null;
    }

    public static Result FileServiceUpload(MultipartFile file, String path) throws IOException {
        String url = baseUrl + "/upload";
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 临时存储在本地
        String fileName = UUID.randomUUID().toString() ;
        Path tempFilePath = Files.createTempFile("temp", fileName);
        FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(String.valueOf(tempFilePath)));

        // 构建请求体
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new FileSystemResource(tempFilePath));
        body.add("path", path);

        // 创建HttpEntity
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 发起POST请求
        ResponseEntity<Result> response = restTemplate.postForEntity(url, requestEntity, Result.class);

        // 删除临时文件
        Files.deleteIfExists(tempFilePath);
        return response.getBody();
    }
}
